<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="销售合同号" prop="saleContractNum">
              <el-input v-model="queryParams.saleContractNum" placeholder="请输入销售合同号" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="运输路段" prop="transportSection">
              <el-select v-model="queryParams.transportSection" placeholder="请选择运输路段" clearable>
                <el-option v-for="dict in transport_section" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="客户" prop="customerId">
              <customer-select v-model:customerId="queryParams.customerId" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table :data="flatRows" height="500" border style="width: 100%; border: 1px solid #000;" :span-method="spanMethod">
        <!-- 主表字段 -->
        <el-table-column prop="saleContractNum" label="销售合同号" align="center" width="120"/>
        <el-table-column prop="projectName" label="项目名称" align="center"/>
        <el-table-column prop="saleCurrency" label="币种" align="center">
          <template #default="scope">
            {{ bas_currency.find(dict => dict.value == scope.row.saleCurrency)?.label }}
          </template>
        </el-table-column>
        <el-table-column prop="transportSection" label="运输路段" align="center">
          <template #default="scope">
            {{ transport_section.find(dict => dict.value == scope.row.transportSection)?.label }}
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" align="center"/>
        <el-table-column prop="contractLocalTotalAmount" label="本币价税合计" align="center" width="120"/>
        <el-table-column prop="contractLocalAmount" label="本币无税金额" align="center" width="120"/>
        <el-table-column prop="contractLocalTaxedAmount" label="本币税额" align="center" width="120"/>

        <!-- 销售开票明细 -->
        <el-table-column label="销售发票明细" align="center">
          <el-table-column prop="saleInvoiceDate" label="发票入账日期" align="center" width="120">
            <template #default="scope">
            <span>{{ parseTime(scope.row.saleInvoiceDate, '{y}-{m}-{d}') }}</span>
          </template>
          </el-table-column>
          <el-table-column prop="saleInvoiceAmount" label="本币价税合计" align="center" width="120"/>
          <el-table-column prop="saleInvoiceVoucher" label="凭证号" align="center"/>
        </el-table-column>

        <!-- 收款明细 -->
        <el-table-column label="收款明细" align="center">
          <el-table-column prop="receiveDate" label="收款入账日期" align="center" width="120">
            <template #default="scope">
            <span>{{ parseTime(scope.row.receiveDate, '{y}-{m}-{d}') }}</span>
          </template>
          </el-table-column>
          <el-table-column prop="receiveAmount" label="收款金额" align="center"/>
          <el-table-column prop="receiveVoucher" label="相关凭证号" align="center" width="120"/>
        </el-table-column>

        <!-- 采购合同 -->
        <el-table-column label="采购合同" align="center">
          <el-table-column prop="purchaseContractNum" label="采购合同号" align="center" width="120"/>
          <el-table-column prop="supplierName" label="供应商名称" align="center" width="120"/>
          <el-table-column prop="purchaseCurrency" label="币种" align="center">
          <template #default="scope">
            {{ bas_currency.find(dict => dict.value == scope.row.purchaseCurrency)?.label }}
          </template>
        </el-table-column>
          <el-table-column prop="purchaseLocalTotalAmount" label="本币价税合计" align="center" width="120"/>
          <el-table-column prop="purchaseLocalAmount" label="本币无税金额" align="center" width="120"/>
          <el-table-column prop="purchaseLocalTaxedAmount" label="本币税额" align="center" width="120"/>
        </el-table-column>

        <!-- 采购开票明细 -->
        <el-table-column label="采购发票明细" align="center">
          <el-table-column prop="purchaseInvoiceDate" label="发票入账日期" align="center" width="120">
            <template #default="scope">
            <span>{{ parseTime(scope.row.purchaseInvoiceDate, '{y}-{m}-{d}') }}</span>
          </template>
          </el-table-column>
          <el-table-column prop="purchaseInvoiceAmount" label="本币价税合计" align="center" width="120"/>
          <el-table-column prop="purchaseInvoiceVoucher" label="相关凭证号" align="center" width="120"/>
        </el-table-column>

        <!-- 付款明细 -->
        <el-table-column label="付款明细" align="center">
          <el-table-column prop="paymentDate" label="付款入账日期" align="center" width="120">
            <template #default="scope">
            <span>{{ parseTime(scope.row.paymentDate, '{y}-{m}-{d}') }}</span>
          </template>
          </el-table-column>
          <el-table-column prop="paymentAmount" label="金额" align="center"/>
          <el-table-column prop="paymentVoucher" label="相关凭证号" align="center" width="120"/>
        </el-table-column>
      </el-table>

    </el-card>
  </div>
</template>
<script setup lang="ts">
import { listReportData } from '@/api/finance/report';
import { exportReportExcel } from '@/utils/exportToExcel';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { transport_section, bas_currency } = toRefs<any>(proxy?.useDict('transport_section', 'bas_currency'));
const showSearch = ref(true);

const contracts = ref<any[]>([]);
const queryParams = reactive({
  saleContractNum: '',
  projectName: '',
  transportSection: '',
  customerId: ''
})
const handleQuery = () => {
  getList();
}
const resetQuery = () => {
  queryParams.saleContractNum = '';
  queryParams.projectName = '';
  queryParams.transportSection = '';
  queryParams.customerId = '';
  getList();
}
const getList = async () => {
  const res = await listReportData(queryParams);
  contracts.value = res.data;
}
onMounted(() => {
  getList();
})

type FlatRow = {
  // 销售合同主表
  saleContractId: string
  saleContractNum: string
  projectName: string
  transportSection: number
  customerName: string
  saleCurrency: number
  contractLocalTotalAmount: string
  contractLocalAmount: string
  contractLocalTaxedAmount: string

  // 销售发票 & 收款（按整体行号对齐）
  saleInvoiceDate: string
  saleInvoiceAmount: string
  saleInvoiceVoucher: string

  receiveDate: string
  receiveAmount: string
  receiveVoucher: string

  // 采购合同（块内合并）
  purchaseContractId?: string | null
  purchaseContractNum: string
  supplierName: string
  purchaseCurrency: number | string
  purchaseLocalTotalAmount: string | null
  purchaseLocalAmount: string
  purchaseLocalTaxedAmount: string

  // 采购发票 & 付款（和采购合同块逐行对应）
  purchaseInvoiceDate: string
  purchaseInvoiceAmount: string
  purchaseInvoiceVoucher: string

  paymentDate: string
  paymentAmount: string
  paymentVoucher: string

  // ===== 合并辅助：采购合同块 =====
  __pcGroupKey?: string   // 唯一标识某个采购合同块（同销售合同内）
  __pcIsFirst?: boolean   // 当前行是否该块的第一行
  __pcRows?: number       // 该块总行数
}

/** ====== 扁平化：堆叠采购合同块，并与销售发票/收款整体对齐 ====== */
const flatRows = computed<FlatRow[]>(() => {
  const rows: FlatRow[] = []

  contracts.value.forEach(contract => {
    const saleInvoices = contract.saleInvoiceDetails ?? []
    const receives     = contract.receiveBills ?? []

    // 先把所有采购合同展开成“块”并串起来
    const purchaseBlocks: FlatRow[] = []
    ;(contract.purchaseContracts ?? []).forEach(pc => {
      const pi = pc.purchaseInvoiceDetails ?? []
      const pay = pc.paymentBills ?? []
      const blockRows = Math.max(1, pi.length, pay.length)

      for (let j = 0; j < blockRows; j++) {
        purchaseBlocks.push({
          // 主表先留空：最终拼装时再补主表字段
          saleContractId: '',
          saleContractNum: '',
          projectName: '',
          customerName: '',
          transportSection: 0,
          saleCurrency: 0,
          contractLocalTotalAmount: '',
          contractLocalAmount: '',
          contractLocalTaxedAmount: '',

          // 销售开票/收款：先空，最终拼装按全局行号再填
          saleInvoiceDate: '',
          saleInvoiceAmount: '',
          saleInvoiceVoucher: '',
          receiveDate: '',
          receiveAmount: '',
          receiveVoucher: '',

          // 采购合同（每一行都带值，后续由 spanMethod 合并显示）
          purchaseContractId: pc.purchaseContractId,
          purchaseContractNum: pc.purchaseContractNum,
          supplierName: pc.supplierName,
          purchaseCurrency: pc.purchaseCurrency,
          purchaseLocalTotalAmount: pc.purchaseLocalTotalAmount,
          purchaseLocalAmount: pc.purchaseLocalAmount,
          purchaseLocalTaxedAmount: pc.purchaseLocalTaxedAmount,

          // 采购发票 & 付款：块内逐行对应
          purchaseInvoiceDate:   pi[j]?.invoiceRecordDate ?? '',
          purchaseInvoiceAmount: pi[j]?.invoiceLocalTotalAmount ?? '',
          purchaseInvoiceVoucher:pi[j]?.invoiceVoucherNum ?? '',

          paymentDate:  pay[j]?.paymentRecordDate ?? '',
          paymentAmount:pay[j]?.paymentAmount ?? '',
          paymentVoucher:pay[j]?.paymentVoucherNum ?? '',

          __pcGroupKey: `${contract.saleContractId}__${pc.purchaseContractNum}`,
          __pcIsFirst: j === 0,
          __pcRows: blockRows
        })
      }
    })

    // 计算整体行数：销售发票/收款 与 所有采购块 的最大
    const overallRows = Math.max(
      Math.max(saleInvoices.length, receives.length, 1),
      purchaseBlocks.length
    )

    // 逐行拼装：左侧主表 + 中间销售发票/收款 + 右侧采购块
    for (let r = 0; r < overallRows; r++) {
      const purchasePart = purchaseBlocks[r] // 可能为 undefined

      rows.push({
        // 主表：每行都放值，显示由 spanMethod 决定合并
        saleContractId: contract.saleContractId,
        saleContractNum: contract.saleContractNum,
        projectName: contract.projectName,
        customerName: contract.customerName,
        transportSection: contract.transportSection,
        saleCurrency: contract.saleCurrency,
        contractLocalTotalAmount: contract.contractLocalTotalAmount,
        contractLocalAmount: contract.contractLocalAmount,
        contractLocalTaxedAmount: contract.contractLocalTaxedAmount,

        // 销售开票明细（按全局行号对齐）
        saleInvoiceDate:    saleInvoices[r]?.invoiceRecordDate ?? '',
        saleInvoiceAmount:  saleInvoices[r]?.invoiceLocalTotalAmount ?? '',
        saleInvoiceVoucher: saleInvoices[r]?.invoiceVoucherNum ?? '',

        // 收款明细（按全局行号对齐）
        receiveDate:   receives[r]?.receiveRecordDate ?? '',
        receiveAmount: receives[r]?.receiveAmount ?? '',
        receiveVoucher:receives[r]?.receiveVoucherNum ?? '',

        // 采购合同块（若没有则空）
        purchaseContractId:    purchasePart?.purchaseContractId,
        purchaseContractNum:   purchasePart?.purchaseContractNum ?? '',
        supplierName:          purchasePart?.supplierName ?? '',
        purchaseCurrency:      purchasePart?.purchaseCurrency ?? '',
        purchaseLocalTotalAmount: purchasePart?.purchaseLocalTotalAmount ?? '',
        purchaseLocalAmount:      purchasePart?.purchaseLocalAmount ?? '',
        purchaseLocalTaxedAmount: purchasePart?.purchaseLocalTaxedAmount ?? '',

        // 采购发票 & 付款（随块逐行）
        purchaseInvoiceDate:    purchasePart?.purchaseInvoiceDate ?? '',
        purchaseInvoiceAmount:  purchasePart?.purchaseInvoiceAmount ?? '',
        purchaseInvoiceVoucher: purchasePart?.purchaseInvoiceVoucher ?? '',

        paymentDate:   purchasePart?.paymentDate ?? '',
        paymentAmount: purchasePart?.paymentAmount ?? '',
        paymentVoucher:purchasePart?.paymentVoucher ?? '',

        __pcGroupKey: purchasePart?.__pcGroupKey,
        __pcIsFirst:  purchasePart?.__pcIsFirst,
        __pcRows:     purchasePart?.__pcRows
      })
    }
  })

  return rows
})

/** ====== 分组合并：销售合同整组、采购合同块内 ====== */
const mainCols = new Set([
  'saleContractNum',
  'projectName',
  'customerName',
  'transportSection',
  'saleCurrency',
  'contractLocalTotalAmount',
  'contractLocalAmount',
  'contractLocalTaxedAmount'
])

const purchaseCols = new Set([
  'purchaseContractNum',
  'supplierName',
  'purchaseCurrency',
  'purchaseLocalTotalAmount',
  'purchaseLocalAmount',
  'purchaseLocalTaxedAmount'
])

// 预计算：销售合同的起始行与行数（连续分组）
const contractGroupMap = computed(() => {
  const map = new Map<string, { start: number; count: number }>()
  flatRows.value.forEach((r, idx) => {
    const key = r.saleContractId
    if (!map.has(key)) map.set(key, { start: idx, count: 0 })
    map.get(key)!.count += 1
  })
  return map
})

const spanMethod = ({
  row,
  column,
  rowIndex
}: {
  row: FlatRow
  column: any
  rowIndex: number
}) => {
  // 1) 销售合同信息：按销售合同整组合并
  if (mainCols.has(column.property)) {
    const g = contractGroupMap.value.get(row.saleContractId)
    if (!g) return { rowspan: 1, colspan: 1 }
    if (rowIndex === g.start) return { rowspan: g.count, colspan: 1 }
    return { rowspan: 0, colspan: 0 }
  }

  // 2) 采购合同信息：只在各自采购块的第一行合并块内行数
  if (purchaseCols.has(column.property)) {
    // 没有采购数据的行，不合并
    if (!row.__pcGroupKey) return { rowspan: 1, colspan: 1 }
    if (row.__pcIsFirst) {
      const rows = row.__pcRows ?? 1
      return { rowspan: rows, colspan: 1 }
    }
    return { rowspan: 0, colspan: 0 }
  }

  // 3) 其它列不合并
  return { rowspan: 1, colspan: 1 }
}
const handleExport=()=> {
  exportReportExcel(flatRows.value)
}
</script>

<style scoped>
:deep(.el-table__row),
:deep(.el-table__header th),
:deep(.el-table__body td) {
  border-bottom: 2px solid #000 !important;
}

:deep(.el-table__row td),
:deep(.el-table__header th) {
  border-right: 2px solid #000 !important;
}
</style>
